package cn.stylefeng.guns.modular.gridsystem.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.stylefeng.guns.core.context.constant.ConstantContextHolder;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 声纹引擎工具类
 * @author ssy
 * @date 2021/11/10 9:30
 */
@Slf4j
public class EngineUtil {

    private static String engineAddress = ConstantContextHolder.getEngineAddress();

    /**
     * 1:N 返回一个匹配
     * @param path
     * @param groupId
     * @return
     */
    public static synchronized String recognize(String path,String groupId){
        File file = FileUtil.file(path);
        Map<String,Object> map = new HashMap<>();
        map.put("type",0);
        map.put("groupId",groupId);
        map.put("myfiles",file);
        String post = HttpUtil.post(engineAddress + "/recognize", map,20000);
        log.info("调用引擎：{}{}",engineAddress,"/recognize");
        log.info("分组号：{}",groupId);
        return post;
    }

    /**
     * 删除模型
     * @param accessToken
     * @param groupId
     * @return
     */
    public static String delete(String accessToken,String groupId){
        Map<String,Object> map = new HashMap<>();
        map.put("accessToken",accessToken);
        map.put("groupId",groupId);
        String post = HttpUtil.post(engineAddress + "/delete", map,5000);
        log.info("删除模型：accessToken:{},groupId：{}",accessToken,groupId);
        return post;
    }

    /**
     * 注册模型
     * @param accessToken
     * @param groupId
     * @param files
     * @return
     */
    public static String register(String accessToken,String groupId,File[] files){
        Map<String,Object> map = Maps.newHashMap();
        map.put("accessToken",accessToken);
        map.put("groupId",groupId);
        map.put("myfiles",files);
        String post;
        if(files.length==1){
            post = HttpUtil.post(engineAddress + "/register", map,20000);
        }else {
            post = HttpUtil.post(engineAddress + "/enroll", map,20000);
        }
        log.info("注册模型：{}",post);
        return post;
    }

}
